package com.fire.chat.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fire.chat.cache.AuthorityCacheStrategy;
import com.fire.chat.constant.CacheConstant;
import com.fire.chat.dao.SysUserRoleRefMapper;
import com.fire.chat.entity.bo.SysUserRoleBO;
import com.fire.chat.entity.po.SysUserRoleRef;
import com.fire.chat.service.SysMenuService;
import com.fire.chat.service.SysUserRoleRefService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>标题: 用户角色表 Service 实现类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2020</p>
 *
 * @version: 1.0
 * @author: xiejiarong
 * @date 2020-11-04
 */
@Service
public class SysUserRoleRefServiceImpl extends ServiceImpl<SysUserRoleRefMapper, SysUserRoleRef> implements SysUserRoleRefService {

    @Autowired(required = false)
    AuthorityCacheStrategy authorityCacheStrategy;

    @Autowired
    @Qualifier("taskExecutor")
    private ThreadPoolTaskExecutor executorService;

    @Autowired
    SysMenuService sysMenuService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliverRights(SysUserRoleBO userRoleBO) {
        //物理删除该用户的所有关联角色
        super.remove(Wrappers.<SysUserRoleRef>lambdaUpdate().eq(SysUserRoleRef::getUserId,userRoleBO.getUid()));
        List<SysUserRoleRef> collect = userRoleBO.getRoleIds().stream().map(data -> {
            SysUserRoleRef sysUserRoleRef = new SysUserRoleRef();
            sysUserRoleRef.setUserId(userRoleBO.getUid());
            sysUserRoleRef.setRoleId(data);
            return sysUserRoleRef;
        }).collect(Collectors.toList());
        super.saveBatch(collect);
        //刷新用户缓存
        if (authorityCacheStrategy!=null){
            authorityCacheStrategy.remove(String.format("%s:%s", CacheConstant.USER_KEY_PREFIX,userRoleBO.getUid()));
            executorService.execute(()->{
                sysMenuService.queryMenuByUserId(userRoleBO.getUid());
            });
        }
    }
}
